#include "webengineview.h"

#include "mediawikiwindow.h"

#include <QAction>
#include <QFileDialog>
#include <QKeyEvent>
#include <QTextEdit>
#include <QWebEngineProfile>



WebEngineView::WebEngineView(QWidget *parent) : QWebEngineView(parent)
{
    connect(pageAction(QWebEnginePage::ViewSource), &QAction::triggered, this, [this](){
        auto edit = new QTextEdit();

        page()->toHtml([edit](QString html){
            edit->setPlainText(html);
            edit->show();
        });
    });

    connect(pageAction(QWebEnginePage::OpenLinkInNewBackgroundTab), &QAction::triggered, this, [this](){
        auto edit = new QTextEdit();

        page()->toHtml([edit](QString html){
            edit->setPlainText(html);
            edit->show();
        });
    });

    connect(page()->profile(), &QWebEngineProfile::downloadRequested, this, [this](QWebEngineDownloadItem *download){
        if (download) {
            auto path = download->downloadFileName();
            auto suffix = QFileInfo(path).suffix();
            path = QFileDialog::getSaveFileName(this, "保存文件", path, "*."+suffix);
            if (path.isEmpty() == false) {
                download->setDownloadFileName(path);
                download->accept();
            }
        }
    });
}

void WebEngineView::showMax()
{
    setParent(nullptr);
    showFullScreen();
    keypress = new KeyPressEater([this](QKeyEvent *event){
        if (event->key() == Qt::Key_F11 && this->parent() == nullptr) {
            showOrigin();
            keypress->deleteLater();
            return true;
        }
        return false;
    }, focusProxy());
}

void WebEngineView::showOrigin()
{
    m_origin_ui->do2();
}

void WebEngineView::setOrigin_ui(MediaWikiWindow *newOrigin_ui)
{
    m_origin_ui = newOrigin_ui;
}

void WebEngineView::focusInEvent(QFocusEvent *event)
{
    qDebug() << "focusInEvent";
}

void WebEngineView::focusOutEvent(QFocusEvent *event)
{
    qDebug() << "focusOutEvent";
}

QWebEngineView *WebEngineView::createWindow(QWebEnginePage::WebWindowType type)
{
    if (type == QWebEnginePage::WebBrowserTab) {
        return this;
    }
    return nullptr;
}
